//
//  PaymentViewController.m
//  wtshoppingcite
//
//  Created by TW on 14-11-7.
//  Copyright (c) 2014年 TW. All rights reserved.


#import "PaymentViewController.h"
#import "RegisterHelper.h"
#import "ShoppingCartModel.h"
#import "Order.h"
#import "DataSigner.h"
#import <AlipaySDK/AlipaySDK.h>

#pragma mark 商城的支付宝信息
#define kPartner  @"2088711360830586"
#define kSeller   @"tongwang2014@126.com"
#define kPrivateKey  @"MIICeAIBADANBgkqhkiG9w0BAQEFAASCAmIwggJeAgEAAoGBANhd2Z+rLaKbcCCTkZEGIpPsZqJ0hidgMs8CuWShHdaqEa2ng0BcP1JZpAX2S24SCEqYGqcSJC6AHlt8bkKXUKEOinlOsYSJ+umOg/Lfhl14mDT72uyTtLVmToNBc8Zcydhi92zyQS997uAZZmoz3fl3/BgMiAB0GfhI6sb+n2tNAgMBAAECgYEAphQ71Kyvhc5sXgUHylr8NbFTAsYQp67WsUG1DsIBRmIa2cHoJIHqdQqrtYvdUGr1BFUGuFFbhnn/U1gKxoCheOR/2S/4bw3fi/CDloXg+zZvDyrPK5D9PoO4aB0+WkHGwk7Ip+ZO0DU6yEa1pzyKA9vwhD9oZb2zvcwepDoJX30CQQD9oqV/vTHuXTCYD3NahM3zLu91kwIluQfaJG7ECUOosMKpLf4lVUNbhNdPFnUtfj2huYyDETTwxcWca/Eg1VTbAkEA2mJBB05sLFkb6sx153WnkHklZL4zmQv9lOxBULJvcjyTJ9SlONL+etrwwfobUDAhLb4HFPwVjT6smIOTmX9k9wJBAMwfBIBMPA3wc7Y84QIdVT38LPz7hcPkKHyXy4j7R7dQIilTeXCEMQRLYZglo8IsEd/A22N0Cp4nHEUp3dIlvfcCQD1Xxh5wR/B5I19kCWZ35RavAPL4fnPqK1PuvTYWuTlkjI1urO52TidiYqiKQavXqSo5K7IYUVF4nnDE3OwMHecCQQCTGQZ3srMHCY+MtKiT4lVJizfAKTBdMFICuezstdV/xbi185QS2cYUVmYphQEew/n9wrxDlsSiVk7ObbCdE53s"

#define kShoppingPayFor  @"http://boss.ldhome.com.cn/pay/alipayMobileQuickPayAsynNotify.action"


#pragma mark 物业的支付宝信息

#define kManagePayFor @"http://boss.ldhome.com.cn/propertyOrder/comnityAlipayCallback.action"

@interface PaymentViewController ()<UITableViewDataSource,UITableViewDelegate>
{
    UITableView *paymentTableView;
}
@property(nonatomic,strong)NSString *partner;//物业信息
@property(nonatomic,strong)NSString *alipayKey;
@property(nonatomic,strong)NSString *sellerId;
@property(nonatomic,assign)NSString *failure;
@end

@implementation PaymentViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self initWithView];
    [self setTitleView:@"付款"];
    
      _result = @selector(paymentResult:);
    
    // Do any additional setup after loading the view.
}

-(void)initWithView{
    
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kWidth, 80)];
    view.backgroundColor = UIColorFromRGB(0xdcdddd);
    [self.view addSubview:view];
    
    
    UILabel *totalLabel = [[UILabel alloc ]initWithFrame:CGRectMake(10, (80 - 40-20)/2, 130, 40)];
    totalLabel.font = [UIFont systemFontOfSize:15.0f];
    totalLabel.text = @"支付总金额";
    totalLabel.backgroundColor = [UIColor clearColor];
    totalLabel.textColor = MAIN_BLACK_COLOR;
    [view addSubview:totalLabel];
    
    UILabel *totalPrice = [[UILabel alloc ]initWithFrame:CGRectMake(10, (80 - 40-20)/2, 130, 40)];
    totalPrice.right = kWidth - 15;
    totalPrice.font = [UIFont systemFontOfSize:15.0f];
    totalPrice.text = [NSString stringWithFormat:@"%@元",self.totalPrice];
    totalPrice.backgroundColor = [UIColor clearColor];
    totalPrice.textColor = MAIN_BLACK_COLOR;
    [view addSubview:totalPrice];
    
    UILabel *seperateLabel = [[UILabel alloc]init];
    seperateLabel.text = @"选择支付方式";
    seperateLabel.font = [UIFont systemFontOfSize:12.0f];
    seperateLabel.textColor = MAIN_BLACK_COLOR;
    seperateLabel.frame = CGRectMake(0,80 - 20, kWidth, 20);
    seperateLabel.backgroundColor = UIColorFromRGB(0x9fa0a0);
    seperateLabel.alpha =0.2;
    [view addSubview:seperateLabel];
    
    paymentTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, view.bottom, kWidth, kHeight - view.height-64) style:UITableViewStylePlain];
    paymentTableView.delegate = self;
    paymentTableView.dataSource = self;
    paymentTableView.separatorStyle = UITableViewCellSelectionStyleNone;
    [self.view addSubview:paymentTableView];
    
    if (_type == NSShoppingPayForStyle) {
        if ([self.orders isEqual:@""] || self.orders == nil){
            
            [self getProductsOrder];
        }
    }else if (_type == NSManageFeePayForStyle){
        [self getPayforInfo];
        self.orders = self.billsModel.propertyOrderId;
    }
   
}

#pragma mark 获取物业的支付信息
-(void)getPayforInfo{
    
    NSString *cid = [RegisterHelper shareHelper].citesId;
    
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    SetValueForKey(params, cid, @"cid");
    
    [NetWorkService byRequestWithAPIPrefix:kBaseAppUrl
                              andAPISuffix:kComnityAlipayInfo
                             andHttpMethod:@"POST"
                             andParameters:params
                           andRequestCache:NO
                            andUseParamDic:YES
                       andPostDataEncoding:MKNKPostDataEncodingTypeJSON
                     andRequestFinishBlock:^(BYRequest *request, BYResponse *response) {
                         
                         if (response.isError) {
                             
                             DLog(@"error %@",response.errorMessage);
                             
                         }else{
                             
                             NSDictionary *responseDic = request.responseJSON;
                             DLog(@"成功数据:%@",responseDic);
                              
                             NSDictionary *ordersArray = [responseDic objectForKey:@"alipay"];

                             self.partner = [ordersArray objectForKey:@"partner"];
                             self.alipayKey = [ordersArray objectForKey:@"alipayKey"];
                             self.failure = [ordersArray objectForKey:@"failure"];
                             self.sellerId = [ordersArray objectForKey:@"sellerId"];
                         }
                     }];

}

#pragma mark getProductsOrder 获取订单号
-(void)getProductsOrder{
    
   NSMutableDictionary *params = [NSMutableDictionary dictionary];
    
    NSMutableArray *product =[NSMutableArray arrayWithCapacity:1];
   

    if (self.isPurchase) {
        
        for (int i = 0; i < _productsArray.count; i++) {
            NSMutableDictionary *dic = [NSMutableDictionary dictionary];
            ShoppingCartModel *shoppingCartModel = _productsArray[i];
            NSString *number =[[RegisterHelper shareHelper].shopCarNumbers objectForKey:shoppingCartModel.sid];
            
            SetValueForKey(dic,number, @"number");
            SetValueForKey(dic, shoppingCartModel.sid, @"productId");
            SetValueForKey(params, @"2", @"orderType");
            [product addObject:dic];
        }
        
       // SetValueForKey(params, product, @"products");
        
    }else{
        
        NSMutableDictionary *dic = [NSMutableDictionary dictionary];
        
        if (_isMyOrder) {
            SetValueForKey(dic, _myOrderItems.productId, @"productId");
            SetValueForKey(dic, _myOrderItems.count, @"number");
        }else{
            NSString *number = [NSString stringWithFormat:@"%d",self.i];
            SetValueForKey(dic,number, @"number");
            SetValueForKey(dic, self.shoppingModel.sid, @"productId");
        }
        [product addObject:dic];
        if ([RegisterHelper shareHelper].type == 1) {
             SetValueForKey(params, @"1", @"orderType");
        }else if ([RegisterHelper shareHelper].type == 2){
            SetValueForKey(params, @"2", @"orderType");
        }
        
    }
    
    NSString *shipId = [RegisterHelper shareHelper].addressModel.shipId;
    NSString *userId = [RegisterHelper shareHelper].userId;
    
    SetValueForKey(params, userId, @"userId");
    SetValueForKey(params, self.totalPrice, @"totalCost");
    SetValueForKey(params, product, @"products");
    SetValueForKey(params, shipId,@"shipId");
   
    
    [NetWorkService byRequestWithAPIPrefix:kBaseAppUrl
                              andAPISuffix:kOrder
                             andHttpMethod:@"POST"
                             andParameters:params
                           andRequestCache:NO
                            andUseParamDic:YES
                       andPostDataEncoding:MKNKPostDataEncodingTypeJSON
                     andRequestFinishBlock:^(BYRequest *request, BYResponse *response) {
                         
                         if (response.isError) {
                             
                             DLog(@"error %@",response.errorMessage);
                             
                         }else{
                             
                             NSDictionary *responseDic = request.responseJSON;
                             NSArray *ordersArray = [responseDic objectForKey:@"orders"];
                             self.orders = [ordersArray objectAtIndex:0];
                             DLog(@"成功数据:%@",responseDic);
                         }
                     }];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    ;
}


- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    
    
}

#pragma mark uitableViewDelegate &datasource
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 60;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return 1;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cellIdentitfer"];
    if (cell == nil) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cellIdentitfer"];
        
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        
        UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(10, 10, 40, 40)];
        [imageView setImage:[UIImage imageNamed:@"alipay_image"]];
        [cell.contentView addSubview:imageView];
        
        UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(imageView.right, 10, 120, 20)];
        label.tag = 100;
        [cell.contentView addSubview:label];
        
        UILabel *subTitlelabel = [[UILabel alloc]initWithFrame:CGRectMake(imageView.right, label.bottom, 180, 20)];
        subTitlelabel.tag = 101;
        subTitlelabel.textColor = UIColorFromRGB(0x95a0a0);
        subTitlelabel.font = [UIFont systemFontOfSize:12.0f];
        [cell.contentView addSubview:subTitlelabel];
        
        _iconButton = [[UIButton alloc]initWithFrame:CGRectMake(10, 60/2 - 10, 20, 20)];
        _iconButton.right = kWidth - 10;
        _iconButton.tag = 102;
        [_iconButton setImage:[UIImage imageNamed:@"alipay"] forState:UIControlStateNormal];
        [cell.contentView addSubview:_iconButton];
        
        UIView *seperateLine = [[UIView alloc]initWithFrame:CGRectMake(2, 60 - 1, kWidth-4, 1)];
        seperateLine.backgroundColor = MAIN_GRAY_COLOR;
        [cell.contentView addSubview:seperateLine];
    }
    
    UILabel *label = (UILabel *)[cell.contentView viewWithTag:100];
    label.text = @"支付宝支付";
    
    UILabel *subTitlelabel = (UILabel *)[cell.contentView viewWithTag:101];
    subTitlelabel.text = @"支付宝账户支付，银行卡支付";
    
    return cell;
}



-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [_iconButton setImage:[UIImage imageNamed:@"alipay_select"] forState:UIControlStateNormal];
    
//    NSString *appScheme = @"TWShoppingCiteDemo";
//    NSString* orderInfo = [self getOrderInfo];
//    NSString* signedStr = [self doRsa:orderInfo];
//    
//    NSLog(@"%@",signedStr);
//    
//    NSString *orderString = [NSString stringWithFormat:@"%@&sign=\"%@\"&sign_type=\"%@\"",
//                             orderInfo, signedStr, @"RSA"];
//    
//    [AlixLibService payOrder:orderString AndScheme:appScheme seletor:_result target:self];
    
    /*
     *商户的唯一的parnter和seller。
     *签约后，支付宝会为每个商户分配一个唯一的 parnter 和 seller。
     */
    
    
    
    /*============================================================================*/
    /*=======================需要填写商户app申请的===================================*/
    /*============================================================================*/
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSString *partner; 
    NSString *seller;
    NSString *privateKey;
    
    if (_type == NSShoppingPayForStyle) {
        partner= kPartner;
        seller = kSeller;
        privateKey = kPrivateKey;
        
    }else if (_type == NSManageFeePayForStyle){
        partner= _partner;
        seller = _sellerId;
        privateKey = _alipayKey;
        
    }
 
    //partner和seller获取失败,提示
    if ([partner length] == 0 || [seller length] == 0)
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示"
                                                        message:@"缺少partner或者seller。"
                                                       delegate:self
                                              cancelButtonTitle:@"确定"
                                              otherButtonTitles:nil];
        [alert show];
        return;
    }
    

    /*
     *生成订单信息及签名
     */
    //将商品信息赋予AlixPayOrder的成员变量
    Order *order = [[Order alloc] init];
    order.partner = partner;
    order.seller = seller;
    
    if (_type == NSShoppingPayForStyle) {
        
        order.notifyURL = kShoppingPayFor; //商城回调URL
        order.tradeNO = self.orders; //订单ID（由商家自行制定）
        order.productName = self.shoppingModel.title; //商品标题
        order.productDescription = self.shoppingModel.subTitle; //商品描述
        order.amount = [NSString stringWithFormat:@"%@",self.totalPrice]; //商品价格

    }else if (_type == NSManageFeePayForStyle){
        
        order.notifyURL =kManagePayFor; //物业回调URL
        order.tradeNO = self.billsModel.propertyOrderId;
        order.productName = @"物业";
        order.productDescription = @"物业缴费";
        order.amount = self.billsModel.totalCost;

    }
    
    order.service = @"mobile.securitypay.pay";
    order.paymentType = @"1";
    order.inputCharset = @"utf-8";
    order.itBPay = @"30m";
    order.showUrl = @"m.alipay.com";
    
    //应用注册scheme,在AlixPayDemo-Info.plist定义URL types
    NSString *appScheme = @"TWShoppingCiteDemo";
    
    //将商品信息拼接成字符串
    NSString *orderSpec = [order description];
    NSLog(@"orderSpec = %@",orderSpec);
    
    //获取私钥并将商户信息签名,外部商户可以根据情况存放私钥和签名,只需要遵循RSA签名规范,并将签名字符串base64编码和UrlEncode
    id<DataSigner> signer = CreateRSADataSigner(privateKey);
    NSString *signedString = [signer signString:orderSpec];
    [self showProgressHUD];
    //将签名成功字符串格式化为订单字符串,请严格按照该格式
    NSString *orderString = nil;
    if (signedString != nil) {
        orderString = [NSString stringWithFormat:@"%@&sign=\"%@\"&sign_type=\"%@\"",
                       orderSpec, signedString, @"RSA"];
        
//        UIView* view = [[[UIApplication sharedApplication] windows] objectAtIndex:0];
//        view.hidden = NO;
//        view.backgroundColor = [UIColor greenColor];
        
        
        [[AlipaySDK defaultService] payOrder:orderString fromScheme:appScheme callback:^(NSDictionary *resultDic) {
            NSLog(@"reslut = %@",resultDic);
            [self hideProgressHUD];
            if ([[resultDic objectForKey:@"resultStatus"] isEqualToString:@"4000"]) {
                __weak PaymentViewController *weak_self = self;
                [weak_self showToastMessage:@"请先下载支付宝"];
            }
            
            if([[resultDic objectForKey:@"resultStatus"] isEqualToString:@"6001"]){
//                UIView* view = [[[UIApplication sharedApplication] windows] objectAtIndex:0];
//                view.hidden = YES;
            }
        }];
    }

}


@end
